﻿// Copyright (c) 2007-2021 西安交通信息投资营运有限公司 版权所有
// 作者:吕艳阳

using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
using XCI.Core;
using XCI.Extensions;
using XCI.Helper;
using XCI.Sys.Forms;
using XCI.Sys.Model;
using XCI.Sys.Service;

namespace XCI.Sys
{
    /// <summary>
    /// 登录窗口管理
    /// </summary>
    public class LoginFormManager
    {
        public static void LoadConfig(ILoginForm loginForm)
        {
            var config = LoginConfig.Get();
            if (loginForm.AutoLoginEdit != null) loginForm.AutoLoginEdit.Checked = config.IsAutoLogin;
            if (loginForm.RememberPasswordEdit != null) loginForm.RememberPasswordEdit.Checked = config.IsRememberPassword;

            if (loginForm.AccountEdit != null) loginForm.AccountEdit.Text = config.Account;
            if (loginForm.PasswordEdit != null)
            {
                try
                {
                    loginForm.PasswordEdit.Text = EncryptHelper.SymmetricDecrypt(config.Password, EncryptHelper.SecretKey);
                }
                catch
                {
                    // ignored
                }
            }
        }

        public static void SaveConfig(ILoginForm loginForm)
        {
            var config = LoginConfig.Get();
            if (loginForm.AutoLoginEdit != null) config.IsAutoLogin = loginForm.AutoLoginEdit.Checked;
            if (loginForm.RememberPasswordEdit != null)
            {
                config.IsRememberPassword = loginForm.RememberPasswordEdit.Checked;
                if (config.IsRememberPassword)
                {
                    if (loginForm.AccountEdit != null) config.Account = loginForm.AccountEdit.Text.Trim();
                    if (loginForm.PasswordEdit != null)
                        config.Password = EncryptHelper.SymmetricEncrypt(loginForm.PasswordEdit.Text, EncryptHelper.SecretKey);
                }
                else
                {
                    config.Account = null;
                    config.Password = null;
                }

            }
            LoginConfig.Save();
        }

        /// <summary>
        /// 自动登录
        /// </summary>
        public static async Task<bool> AutoLoginAsync()
        {
            var isRestart = Startup.IsRestart();
            if (isRestart) return false;

            var config = LoginConfig.Get();
            if (!config.IsAutoLogin) return false;

            string account = config.Account;
            string password = string.Empty;
            try
            {
                password = EncryptHelper.SymmetricDecrypt(config.Password, EncryptHelper.SecretKey);
            }
            catch
            {
                // ignored
            }
            var result = await SysAccountService.Instance.LoginAsync(account, password, string.Empty);
            return OnLoginSuccess(result);
        }

        /// <summary>
        /// 正常登录
        /// </summary>
        public static async Task LoginAsync(ILoginForm loginForm)
        {
            var account = loginForm.AccountEdit.Text.Trim();
            var password = loginForm.PasswordEdit.Text.Trim();
            var captcha = string.Empty;

            if (string.IsNullOrEmpty(account))
            {
                MessageBoxHelper.ShowWarn("请输入帐号");
                loginForm.AccountEdit.Select();
                return;
            }

            if (string.IsNullOrEmpty(password))
            {
                MessageBoxHelper.ShowWarn("请输入密码");
                loginForm.PasswordEdit.Select();
                return;
            }

            try
            {
                loginForm.LoginButton.Enabled = false;
                loginForm.LoadingPanel?.Show();

                var reqCaptcha = await SysAccountService.Instance.RequireCaptchaAsync(account);
                if (reqCaptcha)
                {
                    loginForm.LoadingPanel?.Hide();
                    var capForm = new FrmCaptcha(account);
                    capForm.ShowDialog();
                    captcha = capForm.CaptchaCode;
                    capForm.Dispose();
                }

                loginForm.LoadingPanel?.Show();
                var result = await SysAccountService.Instance.LoginAsync(account, password, captcha);
                loginForm.LoadingPanel?.Hide();

                if (result.Success) loginForm.OwnForm.Hide();
                OnLoginSuccess(result);
                if (result.Success)
                {
                    SaveConfig(loginForm);
                    loginForm.OwnForm.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
            }
            catch (System.Threading.Tasks.TaskCanceledException)
            {
                loginForm.LoadingPanel?.Hide();
                MessageBoxHelper.ShowWarn("连接到服务器超时,请检查网络!");
            }
            catch (HttpRequestException)
            {
                loginForm.LoadingPanel?.Hide();
                MessageBoxHelper.ShowWarn("连接到服务器失败,请检查网络!");
            }
            finally
            {
                loginForm.LoadingPanel?.Hide();
                loginForm.LoginButton.Enabled = true;
            }
        }

        private static bool OnLoginSuccess(BoolResult<SysUser> loginResult)
        {
            var config = LoginConfig.Get();
            if (loginResult.Fail)
            {
                config.IsAutoLogin = false;
                MessageBoxHelper.ShowWarn(loginResult.Msg);
                return false;
            }

            var user = loginResult.Data;
            SysApp.CurrentUser = user;

            if (loginResult.Msg.IsNotEmpty())
            {
                MessageBoxHelper.ShowWarn(loginResult.Msg);
            }

            if (user.PwdNextLoginMustModify)//必须修改密码
            {
                MessageBoxHelper.ShowMessage("为保证您使用系统安全,请先修改密码后再做后续操作");
                var frm = new FrmModifyPassword();
                if (frm.ShowDialog() != DialogResult.OK)
                {
                    Environment.Exit(0);
                }
                frm.Dispose();
            }

            return true;
        }
    }
}